<template>
  <div class="add-edit-content">
    <div class="edit-content" v-if="isEdit">
      <div class="edit-btn-content">
        <el-button type="primary" plain icon="EditPen" @click="handleEditMenu(0)">编 辑</el-button>
        <!-- <el-button type="primary" plain icon="Search" @click="handleEditMenu(1)"
          >进度统计</el-button
        > -->
<!--        <el-button type="primary" plain icon="UserFilled" @click="handleEditMenu(2)"
          >分中心管理员</el-button
        >
        <el-button type="primary" plain icon="UserFilled" @click="handleEditMenu(3)"
          >权限管理员</el-button
        >-->
<!--        <el-button type="primary" plain icon="Calendar" @click="handleEditMenu(4)"
          >预约随访</el-button
        >-->
        <el-button class="unlock-btn" type="warning" plain :icon="form.status === 1 ? Lock : Unlock" @click="handleEditMenu(5)" v-if="form.status != 3"
          >{{ form.status === 1 ? '方案锁定' : '方案解锁' }}</el-button
        >
      </div>
      <div class="edit-form">
        <avue-form :option="editOption" v-model="form">
          <template #DFTZ="{}">
            <div class="DFTZ-content">
              <span style="font-size: 18px; color: #3c8dbc; font-weight: 550">定时随访通知</span>
              <Setting
                style="
                  float: right;
                  width: 20px;
                  height: 20px;
                  margin-top: 7px;
                  color: #00cceb;
                  cursor: pointer;
                "
                @click="handleEditMenu(9)"
              />
              <div class="icon-content">
                <MuteNotification style="width: 200px; height: 200px; color: #dddddd" />
                <span style="color: #958d8d; font-size: 16px">定时通知未开启</span>
              </div>
            </div>
          </template>
          <template #lockStatus="{}">
            <span :style="{ color: ['#409eff', '#e6a23c', 'red'][form.status - 1] }">{{
              form.status == 1 ? '未锁定' : (form.status == 2 ? '已锁定' : '已结束')
            }}</span>
          </template>
        </avue-form>
      </div>
      <div class="edit-footer">
        <!-- <el-button class="unlock-btn" type="warning" plain icon="Open" @click="handleEditMenu(6)"
          >锁 库</el-button
        > -->
        <el-button class="unlock-btn" type="success" plain icon="Lock" @click="handleEditMenu(7)" v-if="form.status != 3"
          >结 束</el-button
        >
        <el-button
          class="unlock-btn"
          type="danger"
          plain
          icon="CloseBold"
          @click="handleEditMenu(8)"
          >删 除</el-button
        >
      </div>
    </div>
    <avue-form v-else :option="options" v-model="form" @submit="handleSubmit">
      <template #menu-form="{ size }">
        <el-button
          :size="size"
          v-if="routerQuery.trialId"
          @click="isEdit = true"
          :icon="ArrowLeftBold"
          >返 回</el-button
        >
      </template>
    </avue-form>
    <setting ref="settingRef" />
    <calendar ref="calendarRef" />
  </div>
</template>
<script setup>
import {
  EditPen,
  ArrowLeftBold,
  Search,
  UserFilled,
  Calendar,
  Lock,
  Open,
  CloseBold,
  Unlock,
} from '@element-plus/icons-vue';
import { enrollmentStatistics } from '@/api/clinicalcase/clinicalCase';
import setting from './setting';
import calendar from './calendar.vue';
import { getList, getDetail, add, update, remove, updateStatus } from '@/api/trial/trial';
import { findObject } from '@smallwei/avue';
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import option from '@/option/trial/trial';
import { useRoute } from 'vue-router';
import { useStore } from 'vuex';
const store = useStore();
const route = useRoute();
const options = ref(option);
const form = ref({});
const routerQuery = ref({});
routerQuery.value = route.query;
const userInfo = computed(() => store.getters.userInfo);
form.value.createUser = userInfo.value.user_id;
let isEdit = ref(false);
let settingRef = ref(null);
let calendarRef = ref(null);
/*
  type：0 编辑
  type：1 进度统计
  type：2 分中心管理员
  type：3 权限管理员
  type：4 预约随访
  type：5 方案锁定
  type：6 锁库
  type：7 结束
  type：8 删除
  type：9 设置
*/
const handleEditMenu = type => {
  if (type === 0) {
    isEdit.value = false;
  }
  if(type === 4){
    nextTick(() => {
      calendarRef.value.open(1);
    })
  }
  if (type === 5) {
    let status = form.value.status === 1 ? 2 : 1;
    let messageText = form.value.status === 1 ? '<strong>方案锁定前请确定数据库结构已经调整为最终版本。</strong><br/><strong>方案锁定后将<span style="color:red">不能修改数据库结构（分组、阶段、CR表）</span>，是否继续进行方案锁定？</strong>' : '<strong>确定将次方案进行解锁？</strong>';
    ElMessageBox.alert(
      messageText,
      '提 示',
      {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确 定',
        // cancelButtonText: '取 消',
        // type: 'warning',
      }
    ).then(() => {
      updateStatus(routerQuery.value.trialId, status).then(res => {
        console.log(res);
        if (res.data.code === 200) {
          ElMessage({
            type: 'success',
            message: '操作成功！',
          });
          initDetail(routerQuery.value.trialId);
        }
      });
    });
  }
  if (type === 6 || type === 7 || type === 8) {
    let messageObj = {
      6: '您确定要将此业务锁库吗？',
      7: '结束后将不可添加被试和采集数据！您确定结束此业务吗？',
      8: '如果业务关联了分层管理，将解除关联并使分层业务失效，重新关联！您确定要删除此业务吗？',
    };
    let messageText = messageObj[type];
    ElMessageBox.confirm(messageText, '提 示', {
      confirmButtonText: '确 定',
      cancelButtonText: '取 消',
      type: 'warning',
    })
      .then(() => {
        if (type === 7) {
          updateStatus(routerQuery.value.trialId, '3').then(res => {
            console.log(res);
            if (res.data.code === 200) {
              ElMessage({
                type: 'success',
                message: '操作成功！',
              });
              initDetail(routerQuery.value.trialId);
            }
          });
        }
      })
      .catch(() => {});
  }
  if (type === 9) {
    nextTick(() => {
      settingRef.value.openSetting();
    });
  }
};
const handleSubmit = (row, done) => {
  if (row.dsfInspector instanceof Array) {
    row.dsfInspector = row.dsfInspector.join(',');
  }
  if (row.dsfSupervisor instanceof Array) {
    row.dsfSupervisor = row.dsfSupervisor.join(',');
  }
  if (row.inspector instanceof Array) {
    row.inspector = row.inspector.join(',');
  }
  if (row.researcher instanceof Array) {
    row.researcher = row.researcher.join(',');
  }
  if (row.supervisor instanceof Array) {
    row.supervisor = row.supervisor.join(',');
  }
  console.log(row);
  add(row)
    .then(() => {
      ElMessage.success('操作成功!');
      initDetail(routerQuery.value.trialId);
      isEdit.value = false;
      done();
    })
    .catch(error => {
      done();
      window.console.log(error);
    });
};
const initDetail = id => {
  if (id) {
    localStorage.removeItem('storageTrialStatus')
    store.commit('SET_TRIAL_STATUS', null);
    getDetail(id).then(res => {
      form.value = res.data.data;
      localStorage.setItem('storageTrialStatus',form.value.status);
      store.commit('SET_TRIAL_STATUS', form.value.status);
    });
  }
};
onMounted(() => {
  initDetail(routerQuery.value.trialId);
  if (routerQuery.value.trialId) {
    isEdit.value = true;
    initEnrollmentStatistics(routerQuery.value.trialId);
  }
});
const enrollmentStatisticsVal = ref({});
const initEnrollmentStatistics = trialId => {
  enrollmentStatistics(trialId).then(res => {
    enrollmentStatisticsVal.value = res.data.data;
    let DATA = res.data.data;
    form.value.YJZL = DATA.totalCaseNum.split('/')[0];
    form.value.SJZL = DATA.totalCaseNum.split('/')[1];
  });
};
const editOption = ref({
  size: 'default',
  labelWidth: 145,
  labelPosition: 'left',
  submitBtn: false,
  emptyBtn: false,
  disabled: true,
  column: [
    {
      label: '业务名称',
      prop: 'name',
      type: 'input',
      span: 9,
    },
    {
      label: '业务状态',
      prop: 'status',
      type: 'select',
      labelWidth: 75,
      dicUrl: '/api/blade-system/dict-biz/dictionary?code=trial_status',
      props: {
        label: 'dictValue',
        value: 'dictKey',
      },
      dataType: "number",
      span: 7,
      // push:1,
    },
    {
      label: '业务方式',
      prop: 'mode',
      type: 'select',
      dicUrl: '/api/blade-system/dict-biz/dictionary?code=scale_mode_type',
      props: {
        label: 'dictValue',
        value: 'dictKey',
      },
      // dicData: [{
      // label: '单中心研究',
      //   value: '1'
      // }, {
      //   label: '多中心研究',
      //   value: '2'
      // }],
      filterable: true,
      overHidden: true,
      labelWidth: 75,
      span: 7,
      // push:1,
    },
    {
      label: '业务类型',
      prop: 'type',
      type: 'select',
      dicUrl: '/api/blade-system/dict-biz/dictionary?code=trial_type',
      props: {
        label: 'dictValue',
        value: 'dictKey',
      },
      span: 9,
    },
    {
      label: '预计总量',
      prop: 'YJZL',
      type: 'input',
      labelWidth: 75,
      span: 7,
    },
    {
      label: '实际总量',
      prop: 'SJZL',
      type: 'input',
      labelWidth: 75,
      span: 7,
    },
    {
      label: '流程模式',
      prop: 'flowPattern',
      type: 'radio',
      dicData: [
        {
          label: '（不固定）诊疗模式',
          value: '1',
        },
        {
          label: '（固定）研究模式',
          value: '2',
        },
      ],
      span: 16,
    },
    {
      label: '',
      prop: 'DFTZ',
      type: 'input',
      labelWidth: 0,
      span: 7,
      slot: true,
    },
    {
      label: '疾病类型',
      prop: 'illness',
      type: 'tree',
      dicUrl: '/api/blade-illness/illness/tree',
      props: {
        label: 'title',
        value: 'id',
      },
      span: 16,
    },
    {
      label: '业务目的与预期结果',
      prop: 'purposeExpectation',
      type: 'input',
      span: 16,
    },
    {
      label: '中心伦理机构',
      prop: 'zxlljg',
      type: 'input',
      span: 16,
    },
    {
      label: '创建时间',
      prop: 'createTime',
      type: 'input',
      span: 16,
    },
    {
      label: '方案锁定',
      prop: 'lockStatus',
      type: 'input',
      span: 16,
      slot: true,
    },
  ],
});
</script>
<style scoped lang="scss">
.add-edit-content {
  width: 90%;
  height: 100%;
}
.edit-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.edit-btn-content {
  margin-bottom: 10px;
}
.unlock-btn {
  float: right;
}
.edit-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
.DFTZ-content {
  width: 100%;
  height: 315px;
  position: absolute;
}
.icon-content {
  width: 100%;
  height: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.edit-form{
  ::v-deep .el-col{
    margin-left: 15px;
  }
}
</style>
